const Koa = require("koa");
const koaStaticCache = require("koa-static-cache");
const koaRouter = require("koa-router");
const koaBody = require("koa-body");
const mysql = require("mysql2/promise");
const app = new Koa();

(async function () {
    // 链接数据库
    const connection = await mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "123456",
        database: "test",
    });

    app.use(
        koaStaticCache({
            prefix: "/public",
            dir: "/public",
            gzip: true,
            dynamic: true,
        })
    );

    const router = new koaRouter();

    router.get("/users", async (ctx, next) => {
        ctx.body = "users";
    });

    // 添加新商品
    router.post("/item", koaBody(), async (ctx, next) => {
        console.log(ctx.request.body);
        let { category_id, name, price, cover, description } = ctx.request.body;
        let res = await connection.query(
            "INSERT INTO `items`(`category_id`, `name`, `price`, `cover`, `description`) VALUES(?,?,?,?,?)",
            [category_id, name, price, cover, description]
        );
        console.log(res);

        ctx.body = "添加成功";
    });

    // 获取商品列表
    router.get("/items", async (ctx, next) => {
        let [items] = await connection.query("SELECT * FROM `items`");

        ctx.body = items;
    });

    // 更新
    router.patch("/item/:id", koaBody(), async (ctx, next) => {
        let { price } = ctx.request.body;
        let { id } = ctx.params;

        let res = await connection.query(
            "UPDATE `items` SET `price` = ? WHERE `id` = ?",
            [price, id]
        );

        ctx.body = "更新成功";
    });

    // 删除
    router.delete("/item/:id", koaBody(), async (ctx, next) => {
        let { id } = ctx.params;

        let res = await connection.query("DELETE FROM `items` WHERE `id` = ?", [
            id,
        ]);

        ctx.body = "删除成功";
    });

    app.use(router.routes());

    app.listen(8080);
})();
